//
//  CNJSon.swift
//  YiZhangGui
//
//  Created by 卢逢卫 on 2024/4/2.
//

import Foundation

public struct CN_Json {

    public static func getDictFromJsonStr(JsonStr: String) -> NSDictionary {
        if let data = JsonStr.data(using: .utf8) {
            do {
                if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? NSDictionary {
                    return jsonArray
                } else {
                    print("Bad Json")
                }
            } catch let error as NSError {
                print(error)
            }
        }
        return NSDictionary()
    }
}

extension CN_Json {

    public static func getJsonStrFromStr(str: String) -> String {
        let jsonStr = "\"" + str + "\""
        return jsonStr
    }

    public static func getJsonStrFromDict(dict: NSDictionary) -> String {
        let jsonData = try! JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
        let jsonString = String(data: jsonData, encoding: String.Encoding.utf8)!
        return jsonString
    }

    public static func getJsonStrFromArray(array: [Any]) -> String {
        let jsonData = try! JSONSerialization.data(withJSONObject: array, options: .sortedKeys)
        let jsonString = String(data: jsonData, encoding: String.Encoding.utf8)!
        return jsonString
    }
}
